<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Question extends Model
{
    /*创建问题*/
    public function add(){
        /*检查是否登录*/
        if(!user_ins()->is_logged_in()){
            return ['status' =>0,'msg'=>'用户未登录！'];
        }

        if (!rq('title')){
            return ['status' =>0,'msg'=>'问题标题为空！'];
        }

        $this->title=rq('title');
        $this->user_id=session('user_id');
        if (rq('desc')){
            $this->desc=rq('desc');
        }
        return $this->save() ?
            ['status' =>1,'id'=>$this->id]:
            ['status' =>0,'msg'=>'DB insert failed'];
    }
    /*更改问题*/
    public function change(){
        /*检查是否登录*/
        if(!user_ins()->is_logged_in()){
            return ['status' =>0,'msg'=>'用户未登录！'];
        }
        /*检查传参中是否有ID*/
        if (!rq('id')){
            return ['status' =>0,'msg'=>'ID为空！'];
        }
        /*获取指定ID的Model*/
        $question = $this->find(rq('id'));
        /*判断问题是否存在*/
        if(!$question){
            return ['status' =>0,'msg'=>'问题不存在！'];
        }
        if ($question->user_id != session('user_id')){
            return ['status' =>0,'msg'=>'当前用户无权限操作！'];
        }
        if (rq('title')){
            $question->title=rq('title');
        }
        if (rq('desc')) {
            $question->desc=rq('desc');
        }
        /*保存数据*/
        return $question->save() ?
            ['status' =>1,'msg'=>'更改成功']:
            ['status' =>0,'msg'=>'更新失败！'];
    }
    /*查看问题api*/
    public function read(){
        /*请求参数中是否有ID，如果有id，直接返回id所在的行*/
        if (rq('id')){
            return ['status'=>1,'data'=>$this->find(rq('id'))];
        }
        /*limit条件*/
        $limit = rq('limit')?:15;
        /*$skip条件，用于分页使用*/
        $skip=(rq('page')?rq('page')-1:0)*$limit;
        /*构建query并返回collection数据，collection数据为一个对象，前端可以直接使用*/
        $r=$this->orderBy('created_at')
            ->limit($limit)
            ->skip($skip)
            ->get(['id','title','desc','user_id','created_at','updated_at'])
            ->keyBy('id');
        return ['status'=>1,'data'=>$r];

    }
    /*删除问题api*/
    public function remove(){
        /*检查用户是否登录*/
        if (!user_ins()->is_logged_in()){
            return ['status'=>0,'msg'=>'请登录后操作！'];
        }
        /*检查传参中是否有ID*/
        if (!rq('id')){
            return ['status'=>0,'msg'=>'问题不存在！'];
        }
        /*获取传参ID对应的model*/
        $question=$this->find(rq('id'));
        if (!$question){
            return ['status'=>0,'msg'=>'问题不存在！'];
        }
        /*检查当前用户是否为问题所有者*/
        if (session('user_id')!=$question->user_id){
            return ['status'=>0,'msg'=>'删除失败，非问题提问者！'];
        }else {
            return $question->delete() ?
                ['status'=>1,'msg'=>'删除成功']:
                ['status'=>0,'msg'=>'操作失败，数据库错误！'];
        }
    }
}
